﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using WebHttpApi.WebHttpApi.Core;

namespace WebHttpApi.WebHttpApi.HttpApi
{
    /// <summary>
    /// TYPostData 的摘要说明：第三方平台数据接入处理类
    /// </summary>
    public class TYPostData
    {
        public static string result(Stream postData)
        {
            string str_result = "";

            if (postData.Length != 0)
            {

                StreamReader sRead = new StreamReader(postData);
                string postContent = sRead.ReadToEnd();

                sRead.Close();
                JObject json_post = (JObject)JsonConvert.DeserializeObject(postContent);
                string str_post_json = TySign.str_json(json_post);

                string str_MeterCode = "";
                string str_Sign = "";
                string str_Secret = "";
                str_MeterCode = json_post["MeterCode"].ToString();
                str_Sign = json_post["Sign"].ToString();
                str_Secret = json_post["Secret"].ToString();

                //水表代码验证
                string sql_check = "select Title,Code,Remark from Sys_Dics where Code='" +
                                str_MeterCode + "' and Remark='" + str_Secret + "' and CategoryId=13";

                System.Data.DataTable Meter_Code = WebSdkCore.select(sql_check);

                if (Meter_Code.Rows.Count > 0)
                {
                    //签名验证、数据入库
                    if (WebSdkCore.GetMD5String(str_post_json) == str_Sign)
                    {
                        string str_MeterID = "";
                        string str_MeterReadingTime = "";
                        string str_PositiveCumulativeFlow = "";
                        string str_PositiveInstantaneousFlow = "";
                        string str_AntiCumulativeFlow = "";
                        string str_AntiInstantaneousFlow = "";
                        string str_PipelinePressure = "";
                        string str_PipelineTemperature = "";
                        string str_ValveStatus = "";
                        string str_BatteryVoltage = "";
                        string str_Malfunction = "";
                        string str_SignalIntensity = "";
                        string str_SNR = "";
                        string str_PCI = "";
                        string str_IMSI = "";
                        string str_IMEI = "";

                        //取值
                        foreach (JToken child in json_post.Children())
                        {
                            var temp = child as JProperty;

                            switch (temp.Name)
                            {
                                case "MeterID":
                                    {
                                        str_MeterID = temp.Value.ToString();
                                        break;
                                    }

                                case "MeterReadingTime":
                                    {
                                        str_MeterReadingTime = Convert.ToDateTime(temp.Value.ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                                        break;
                                    }

                                case "PositiveCumulativeFlow":
                                    {
                                        str_PositiveCumulativeFlow = temp.Value.ToString();
                                        break;
                                    }

                                case "PositiveInstantaneousFlow":
                                    {
                                        str_PositiveInstantaneousFlow = temp.Value.ToString();
                                        break;
                                    }

                                case "AntiCumulativeFlow":
                                    {
                                        str_AntiCumulativeFlow = temp.Value.ToString();
                                        break;
                                    }

                                case "AntiInstantaneousFlow":
                                    {
                                        str_AntiInstantaneousFlow = temp.Value.ToString();
                                        break;
                                    }

                                case "PipelinePressure":
                                    {
                                        str_PipelinePressure = temp.Value.ToString();
                                        break;
                                    }

                                case "PipelineTemperature":
                                    {
                                        str_PipelineTemperature = temp.Value.ToString();
                                        break;
                                    }

                                case "ValveStatus":
                                    {
                                        str_ValveStatus = temp.Value.ToString();

                                        if (str_ValveStatus == "0")
                                        {
                                            str_ValveStatus = "关";
                                        }
                                        else if (str_ValveStatus == "1")
                                        {
                                            str_ValveStatus = "开";
                                        }
                                        else if (str_ValveStatus == "3")
                                        {
                                            str_ValveStatus = "异常";
                                        }
                                        break;
                                    }

                                case "BatteryVoltage":
                                    {
                                        str_BatteryVoltage = temp.Value.ToString();
                                        break;
                                    }

                                case "Malfunction":
                                    {
                                        str_Malfunction = temp.Value.ToString();

                                        string[] str = str_Malfunction.Split(',');
                                        string str_gz_info = "";
                                        string gz_info = "";

                                        //故障
                                        for (int i = 0; i < str.Length; i++)
                                        {
                                            gz_info = "";

                                            switch (str[i])
                                            {
                                                case "1":
                                                    {
                                                        gz_info = "温度传感器异常";
                                                        break;
                                                    }

                                                case "2":
                                                    {
                                                        gz_info = "压力传感器异常";
                                                        break;
                                                    }

                                                case "3":
                                                    {
                                                        gz_info = "缺水或换能器异常";
                                                        break;
                                                    }

                                                case "4":
                                                    {
                                                        gz_info = "持续小流量";
                                                        break;
                                                    }

                                                case "5":
                                                    {
                                                        gz_info = "电池欠压";
                                                        break;
                                                    }

                                                case "6":
                                                    {
                                                        gz_info = "磁干扰";
                                                        break;
                                                    }

                                                default:
                                                    break;
                                            }

                                            if (i == 0)
                                            {
                                                str_gz_info += gz_info;
                                            }
                                            else
                                            {
                                                str_gz_info += "," + gz_info;
                                            }
                                        }

                                        str_Malfunction = str_gz_info;
                                        break;
                                    }

                                case "SignalIntensity":
                                    {
                                        str_SignalIntensity = temp.Value.ToString();
                                        break;
                                    }

                                case "SNR":
                                    {
                                        str_SNR = temp.Value.ToString();
                                        break;
                                    }

                                case "PCI":
                                    {
                                        str_PCI = temp.Value.ToString();
                                        break;
                                    }

                                case "IMSI":
                                    {
                                        str_IMSI = temp.Value.ToString();
                                        break;
                                    }

                                case "IMEI":
                                    {
                                        str_IMEI = temp.Value.ToString();
                                        break;
                                    }
                            }
                        }

                        if (SelectIn(str_MeterID, str_MeterReadingTime, str_PositiveCumulativeFlow))
                        {
                            DateTime str_system_time = DateTime.Now;

                            //净累积流量
                            string str_NetCumulativeFlow = "";
                            str_NetCumulativeFlow = (Convert.ToDecimal(str_PositiveCumulativeFlow) - Convert.ToDecimal(str_AntiCumulativeFlow)).ToString();

                            string sql = "select ybdz from rp_meter_jk where ybdz='" +
                                          str_MeterID + "'";

                            System.Data.DataTable Meter_Data = WebSdkCore.select(sql);

                            if (Meter_Data.Rows.Count > 0)
                            {
                                bool operatorlog = WebSdkCore.insert_update_delete("update rp_meter_jk set ybsj='" +
                                                                                    str_MeterReadingTime + "',zxlj='" +
                                                                                    str_PositiveCumulativeFlow + "',zxss='" +
                                                                                    str_PositiveInstantaneousFlow + "',fxlj='" +
                                                                                    str_AntiCumulativeFlow + "',fxss='" +
                                                                                    str_AntiInstantaneousFlow + "',jlj='" +
                                                                                    str_NetCumulativeFlow + "',gdyl='" +
                                                                                    str_PipelinePressure + "',gdwd='" +
                                                                                    str_PipelineTemperature + "',fmzt='" +
                                                                                    str_ValveStatus + "',ybdy='" +
                                                                                    str_BatteryVoltage + "',gzxs='" +
                                                                                    str_Malfunction + "',xhqz='" +
                                                                                    str_SignalIntensity + "',snr='" +
                                                                                    str_SNR + "',pci='" +
                                                                                    str_PCI + "',imsi='" +
                                                                                    str_IMSI + "',imei='" +
                                                                                    str_IMEI + "',txsj='" +
                                                                                    str_system_time + "' where ybdz='" +
                                                                                    str_MeterID + "'");

                                if (operatorlog == true)
                                {
                                    operatorlog = WebSdkCore.insert_update_delete("insert into rp_meter_sj(ybdz,ybsj,zxlj,zxss,jlj,fxlj,fxss,gdyl,gdwd,fmzt,ybdy,gzxs,xhqz,snr,pci,imsi,imei,txsj) values ('" +
                                                           str_MeterID + "','" +
                                                           str_MeterReadingTime + "','" +
                                                           str_PositiveCumulativeFlow + "','" +
                                                           str_PositiveInstantaneousFlow + "','" +
                                                           str_NetCumulativeFlow + "','" +
                                                           str_AntiCumulativeFlow + "','" +
                                                           str_AntiInstantaneousFlow + "','" +
                                                           str_PipelinePressure + "','" +
                                                           str_PipelineTemperature + "','" +
                                                           str_ValveStatus + "','" +
                                                           str_BatteryVoltage + "','" +
                                                           str_Malfunction + "','" +
                                                           str_SignalIntensity + "','" +
                                                           str_SNR + "','" +
                                                           str_PCI + "','" +
                                                           str_IMSI + "','" +
                                                           str_IMEI + "','" +
                                                           str_system_time + "')");

                                    if (operatorlog == true)
                                    {

                                        /*调整上传数据后，需控制阀门*/
                                        string mlnr = string.Empty;
                                        string commandId = string.Empty;
                                        string state = string.Empty;
                                        string zl = $"select top 1 KeyId, zxjg,mlnr from rp_meter_cx where ybdz='{str_MeterID}' and zxjg=0";
                                        System.Data.DataTable commamd = WebSdkCore.select(zl);
                                        if (commamd.Rows.Count > 0)
                                        {
                                            for (int i = 0; i < commamd.Rows.Count; i++)
                                            {
                                                mlnr = Meter_Data.Rows[i]["mlnr"].ToString();
                                                commandId = Meter_Data.Rows[i]["mlnr"].ToString();
                                            }
                                            if (mlnr == "99") {  state = "开阀"; } else { state = "关阀"; }

                                            var json_result = new
                                            {
                                                StatusCode = "201",
                                                Message = state,
                                                ValveCommand = mlnr,
                                                CommandTpye = commandId
                                            };
                                            str_result = WebSdkCore.ToJSON(json_result);

                                        }
                                        else
                                        {
                                            var json_result = new
                                            {
                                                StatusCode = "200",
                                                Message = "成功"
                                            };
                                            str_result = WebSdkCore.ToJSON(json_result);

                                        }
                                      
                                    }
                                    else
                                    {
                                        var json_result = new
                                        {
                                            StatusCode = "500",
                                            Message = "写数据库失败",
                                        };
                                        str_result = WebSdkCore.ToJSON(json_result);
                                    }
                                }
                                else
                                {
                                    var json_result = new
                                    {
                                        StatusCode = "500",
                                        Message = "写数据库失败",
                                    };
                                    str_result = WebSdkCore.ToJSON(json_result);
                                }
                            }
                            else if (Meter_Data.Rows.Count == 0)
                            {
                                bool operatorlog = WebSdkCore.insert_update_delete("insert into rp_meter_jk(ybdz,ybsj,zxlj,zxss,jlj,fxlj,fxss,gdyl,gdwd,fmzt,ybdy,gzxs,xhqz,snr,pci,imsi,imei,txsj) values ('" +
                                                       str_MeterID + "','" +
                                                       str_MeterReadingTime + "','" +
                                                       str_PositiveCumulativeFlow + "','" +
                                                       str_PositiveInstantaneousFlow + "','" +
                                                       str_NetCumulativeFlow + "','" +
                                                       str_AntiCumulativeFlow + "','" +
                                                       str_AntiInstantaneousFlow + "','" +
                                                       str_PipelinePressure + "','" +
                                                       str_PipelineTemperature + "','" +
                                                       str_ValveStatus + "','" +
                                                       str_BatteryVoltage + "','" +
                                                       str_Malfunction + "','" +
                                                       str_SignalIntensity + "','" +
                                                       str_SNR + "','" +
                                                       str_PCI + "','" +
                                                       str_IMSI + "','" +
                                                       str_IMEI + "','" +
                                                       str_system_time + "')");

                                if (operatorlog == true)
                                {
                                    operatorlog = WebSdkCore.insert_update_delete("insert into rp_meter_sj(ybdz,ybsj,zxlj,zxss,jlj,fxlj,fxss,gdyl,gdwd,fmzt,ybdy,gzxs,xhqz,snr,pci,imsi,imei,txsj) values ('" +
                                                           str_MeterID + "','" +
                                                           str_MeterReadingTime + "','" +
                                                           str_PositiveCumulativeFlow + "','" +
                                                           str_PositiveInstantaneousFlow + "','" +
                                                           str_NetCumulativeFlow + "','" +
                                                           str_AntiCumulativeFlow + "','" +
                                                           str_AntiInstantaneousFlow + "','" +
                                                           str_PipelinePressure + "','" +
                                                           str_PipelineTemperature + "','" +
                                                           str_ValveStatus + "','" +
                                                           str_BatteryVoltage + "','" +
                                                           str_Malfunction + "','" +
                                                           str_SignalIntensity + "','" +
                                                           str_SNR + "','" +
                                                           str_PCI + "','" +
                                                           str_IMSI + "','" +
                                                           str_IMEI + "','" +
                                                           str_system_time + "')");

                                    if (operatorlog == true)
                                    {
                                        var json_result = new
                                        {
                                            StatusCode = "200",
                                            Message = "ok",
                                        };
                                        str_result = WebSdkCore.ToJSON(json_result);
                                    }
                                    else
                                    {
                                        var json_result = new
                                        {
                                            StatusCode = "500",
                                            Message = "写数据库失败",
                                        };
                                        str_result = WebSdkCore.ToJSON(json_result);
                                    }
                                }
                                else
                                {
                                    var json_result = new
                                    {
                                        StatusCode = "500",
                                        Message = "写数据库失败",
                                    };
                                    str_result = WebSdkCore.ToJSON(json_result);
                                }
                            }
                            else
                            {
                                var json_result = new
                                {
                                    StatusCode = "500",
                                    Message = "写数据库失败",
                                };
                                str_result = WebSdkCore.ToJSON(json_result);
                            }
                        }
                        else
                        {
                            //参数错误
                            var json_result = new
                            {
                                StatusCode = "402",
                                Message = "参数错误",
                            };
                            str_result = WebSdkCore.ToJSON(json_result);
                        }
                    }
                    else
                    {
                        var json_result = new
                        {
                            StatusCode = "403",
                            Message = "签名错误",
                        };
                        str_result = WebSdkCore.ToJSON(json_result);
                    }
                }
                else
                {
                    var json_result = new
                    {
                        StatusCode = "401",
                        Message = "不存在的表类型",
                    };
                    str_result = WebSdkCore.ToJSON(json_result);
                }

            }
            else
            {
                //参数为空
                var json_result = new
                {
                    StatusCode = "402",
                    Message = "参数错误",
                };
                str_result = WebSdkCore.ToJSON(json_result);
            }
            return str_result;
        }

        public static bool SelectIn(string meter_number, string value, string upload_time)
        {
            bool result;
            if (string.IsNullOrEmpty(meter_number) || string.IsNullOrEmpty(value) || string.IsNullOrEmpty(upload_time))
            {
                result = false;
            }
            else
            {
                result = true;
            }
            return result;
        }
    }
}